package org.afraid.freedns.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.afraid.freedns.constant.Constants;
import org.afraid.freedns.dto.UserDto;
import org.afraid.freedns.dto.UserLoginDto;
import org.afraid.freedns.dto.UserUpdateDto;
import org.afraid.freedns.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户管理控制层
 * 
 * @author jianggq
 * @date 2018年7月24日下午6:46:35
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private final UserService userService;

	@Autowired
	public UserController(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 代理登录
	 * 
	 * @param loginDto
	 * @return
	 */
	@PostMapping("/login")
	public ModelAndView login(@Valid UserLoginDto loginDto, HttpServletRequest request) {

		UserDto userDto = userService.login(loginDto);

		HttpSession session = request.getSession();// 需要新建session
		session.setAttribute(Constants.USER_SESSION_KEY, userDto);

		return new ModelAndView("ftl/profile", "user", userDto);
	}

	/**
	 * 用户信息修改
	 * 
	 * @param updateDto
	 * @return
	 */
	@PostMapping("/update")
	public ModelAndView update(@Valid UserUpdateDto updateDto, HttpSession session) {
		UserDto userDto = userService.update(updateDto);

		// 更新session
		session.setAttribute(Constants.USER_SESSION_KEY, userDto);

		// 更新成功后
		return new ModelAndView("ftl/profile", "user", userDto);
	}

	/**
	 * 用户信息删除
	 * 
	 * @param updateDto
	 * @return
	 */
	@GetMapping("/delete")
	public ModelAndView delete(@RequestParam Long id, HttpSession session) {
		userService.delete(id);
		return new ModelAndView("ftl/login", "user", session.getAttribute(Constants.USER_SESSION_KEY));
	}
}
